<?php
/**
 * 公共的模型方法
 * Created by ykinfo.net
 * User: zhangbf <zhangbf@ykinfo.net>
 * Date: 2017/6/29  10:02
 */

namespace app\common\model;

use think\Db;
use think\Model;
class Common extends Model
{
    /**
     * 保存或更新数据
     * @param $data
     * @param $table
     * @return bool
     */
    public function saveData($data,$table)
    {
        // 启动事务
        $this->startTrans();
        if(isset($data['id'])&& $data['id']){
            //更新数据
            $id=$data['id'];
            unset($data['id']);
            $data['mtime']=time();
            $res=Db::table($table)
                ->where('id', $id)
                ->update($data);
        }else{
            //保存数据
            $data['id']=uniqid();
            $data['ctime']=time();
            $data['mtime']=time();
            $res=Db::table($table)->insert($data);
        }

        if($res){
            $this->commit();
            return $res !== false;
        }else{
            $this->rollback();
            return $res !== false;
        }

    }

    /**
     * 获取指定的数据
     * @param $need
     * @param $data
     * @return array
     */
    public function getNeed($need,$data){
        $r=[];
        foreach ($need as $k=>$value)
        {
            if(isset($data[$value])){
                $r[$value]=$data[$value];
            }
        }
        return $r;
    }
}